<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Core_Plugin_Template extends Zend_Controller_Plugin_Abstract
{
	protected $template,$layout,$view;
  public function routeShutdown(Zend_Controller_Request_Abstract $request)
  {
		$bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
		$options = $bootstrap->getOptions();
		$this->template = Core_Templates::getInstance()->setOptions(@$options['template']);
		/* View */
		$this->view = $bootstrap->getResource('view');
		$this->view = is_null($this->view)
										?new Zend_View($bootstrap->getOptions())
										:$this->view;

		if(!$this->view instanceof Zend_View)
			throw new Zend_Application_Exception('View must be extends Zend_View');
			
		Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer')
			->setView($this->view);
			
		/* Layout */
		$this->layout = is_null(Zend_Layout::getMvcInstance())
											?Zend_Layout::startMvc($bootstrap->getOptions())
											:Zend_Layout::getMvcInstance();

		if(!$this->layout instanceof Zend_Layout)
			throw new Zend_Application_Exception('Layout must be extends Zend_Layout');

		$this->layout->setLayout($this->template->getLayout());
		$this->layout->setLayoutPath($this->template->getPath());
  }
	public function postDispatch(Zend_Controller_Request_Abstract $request)
	{
		if(is_file($this->template->getPath('config.php')))
		{
			$config = require($this->template->getPath('config.php'));
			if(!empty($config[$this->layout->getLayout()]))
			foreach($config[$this->layout->getLayout()] as $key => $area)
			{
				$items = array();
				if(!empty($area['items']))
				foreach($area['items'] as $widget)
				{
					$items[] = Core_Widget::getWidget($widget)->render();
				}
				if(!empty($items))
				{
					$this->layout->{$key} .= @$area['header'];
					$this->layout->{$key} .= @implode(@$area['spread'], $items);
					$this->layout->{$key} .= @$area['footer'];
				}
			}
		}
	}
}